<template>
  <div>
    <!-- title；弹窗的标题 -->
    <!-- visible：控制弹窗是否可见 -->
    <!-- before-close：弹窗关闭前的回调函数 -->
    <el-dialog
      :title="info.type === 'add' ? '新增商品' : '编辑商品'"
      :visible.sync="info.isShow"
      width="60%"
    >
      <el-tabs v-model="activeName">
        <el-tab-pane label="基本信息" name="first">
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="一级分类" prop="first_cateid">
              <el-select
                v-model="ruleForm.first_cateid"
                @change="firstChange"
                placeholder="请选择"
              >
                <el-option label="请选择" :value="0"></el-option>
                <el-option
                  v-for="item in firstList"
                  :label="item.catename"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="二级分类" prop="second_cateid">
              <el-select v-model="ruleForm.second_cateid" placeholder="请选择">
                <el-option label="请选择" :value="0"></el-option>
                <el-option
                  v-for="item in secondList"
                  :label="item.catename"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商品名称" prop="goodsname">
              <el-input v-model="ruleForm.goodsname"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="price">
              <el-input v-model="ruleForm.price"></el-input>
            </el-form-item>
            <el-form-item label="市场价格" prop="market_price">
              <el-input v-model="ruleForm.market_price"></el-input>
            </el-form-item>
            <el-form-item label="商品图片" prop="img">
              <!-- 上传组件 -->
              <el-upload
                action="#"
                list-type="picture-card"
                :file-list="fileList"
                :limit="1"
                :on-change="handleChange"
                :on-remove="handleRemove"
                :on-exceed="handleExceed"
                :auto-upload="false"
              >
                <i slot="default" class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="商品规格" prop="specsid">
              <el-select
                v-model="ruleForm.specsid"
                placeholder="请选择"
                @change="attrChange"
              >
                <el-option label="请选择" :value="0"></el-option>
                <el-option
                  v-for="item in specsList"
                  :label="item.specsname"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="规格属性值" prop="specsattr">
              <el-select
                v-model="ruleForm.specsattr"
                multiple
                placeholder="请选择"
              >
                <el-option label="请选择" :value="0"></el-option>
                <el-option
                  v-for="item in specsvaluelist"
                  :label="item"
                  :value="item"
                  :key="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否新品" prop="isnew">
              <el-radio v-model="ruleForm.isnew" :label="1">是</el-radio>
              <el-radio v-model="ruleForm.isnew" :label="0">否</el-radio>
            </el-form-item>
            <el-form-item label="是否热卖" prop="ishot">
              <el-radio v-model="ruleForm.ishot" :label="1">是</el-radio>
              <el-radio v-model="ruleForm.ishot" :label="0">否</el-radio>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="ruleForm.status">
                <el-radio :label="1">正常</el-radio>
                <el-radio :label="2">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="详细描述" name="second">
          <!-- 给编辑器准备容器 -->
          <div id="editor"></div>
        </el-tab-pane>
      </el-tabs>
      <el-button v-if="info.type === 'add'" type="primary" @click="submitForm"
        >立即创建</el-button
      >
      <el-button v-else type="primary" @click="submitForm">立即编辑</el-button>
      <el-button @click="resetForm('ruleForm')">重置</el-button>
    </el-dialog>
  </div>
</template>

<script>
// 引入编辑器
import E from "wangeditor";
import {
  getCateListTree,
  getCateListById,
  getSpecsList,
  getSpecsInfo,
} from "../../api";
export default {
  props: ["info"],
  data() {
    return {
      activeName: "first",
      // 一级分类下拉框的数据
      firstList: [],
      // 二级分类下拉框的数据
      secondList: [],
      // 历史文件列表
      fileList: [],
      // 规格属性列表
      specsList: [],
      // 属性值列表
      specsvaluelist: [],
      // 表单中的数据
      ruleForm: {
        first_cateid: 0,
        second_cateid: 0,
        goodsname: "",
        price: 1,
        market_price: 1,
        img: "",
        description: "",
        specsid: 0,
        specsattr: [],
        isnew: 1,
        ishot: 1,
        // 1正常2禁用
        status: 1,
      },
      // 编辑器的实例对象
      editor: null,
      // 校验规则
      rules: {
        roleid: [
          { required: true, message: "请选择角色名称", trigger: "change" },
        ],
        username: [
          { required: true, message: "请输入管理员名称", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    // 获取下拉框中的数据
    this.getCateListTreeFn();
    this.getSpecsListFn();
  },
  methods: {
    // 设置表单的值
    setVal(data) {
      // 深拷贝，避免数据互相影响
      this.ruleForm = { ...data };
      // specsattr 因为可以多选,所以是数组,需要转换格式
      this.ruleForm.specsattr = data.specsattr ? data.specsattr.split(',') : [];
      // 等待 dom加载再创建编辑器
      this.$nextTick(() => {
        // 不能重复创建
        if (!this.editor) {
          // 初始化编辑器
          this.editor = new E("#editor");
          this.editor.create();
        }
        // 设置编辑器中的内容
        this.editor.txt.html(this.ruleForm.description);
      });
      // 编辑时,需要获取二级分类/规格属性值的下拉框数据
      if (this.info.type === "edit") {
        this.firstChange();
        this.attrChange();
      }
    },
    // 修改文件时调用的函数
    handleChange(file) {
      // 每个分类只有一张图，将文件信息传给后台
      this.ruleForm.img = file.raw;
    },
    // 删除文件时调用的函数
    handleRemove() {
      this.ruleForm.img = "";
    },
    // 文件超出个数限制时的钩子
    handleExceed() {
      this.$message.warning(`当前限制选择 1 个文件`);
    },
    async getCateListTreeFn() {
      let res = await getCateListTree();
      this.firstList = res.list;
    },
    async getSpecsListFn() {
      let res = await getSpecsList();
      this.specsList = res.list;
    },
    // 一级分类变化时，要发请求获取他对应的二级数据
    async firstChange() {
      let res = await getCateListById(this.ruleForm.first_cateid);
      this.secondList = res.list;
    },
    // 規格属性变化时，要重新获取对应的属性值
    async attrChange() {
      let res = await getSpecsInfo(this.ruleForm.specsid);
      this.specsvaluelist = res.list[0].attrs;
    },
    submitForm() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          // txt.html() 获取富文本编辑器中的值
          this.ruleForm.description = this.editor.txt.html();
          console.log(this.ruleForm);
          return;
          // 删除多余的数据
          this.ruleForm.firstcatename? delete this.ruleForm.firstcatename : ''
          this.ruleForm.secondcatename? delete this.ruleForm.secondcatename : ''
          this.ruleForm.number? delete this.ruleForm.number : ''
          if (this.info.type === "add") {
            // 添加
            let res = await adminAdd(this.ruleForm);
            if (res.code === 200) {
              this.$message({
                type: "success",
                message: res.msg,
              });
            } else {
              this.$message({
                type: "warning",
                message: res.msg,
              });
            }
            // 关闭弹窗
            this.close();
          } else {
            // 编辑
            let res = await editMenu(this.ruleForm);
            // 关闭弹窗
            this.close();
          }
          // 更新list
          this.$emit("update");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 关闭弹窗
    close() {
      this.info.isShow = false;
    },
  },
};
</script>

<style>
</style>